package com.example.network.monitor;

import java.util.List;

import android.app.Activity;
import android.net.TrafficStats;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

public class SecondActivity extends Activity {
	
	long up;
	long down;
	long zeroUp;
	long zeroDown;
	Handler aHandler;
	TextView text5;
	TextView text6;
	public void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.second);

		WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		List<ScanResult> results = wifiManager.getScanResults();


		//Gets info and puts it in second view's appropriate textView.
		TextView text = (TextView) findViewById(R.id.textView9);
		text.setText(wifiInfo.getSSID());
		TextView text2 = (TextView) findViewById(R.id.textView10);
		text2.setText(wifiInfo.getBSSID());
		//iterate over all available wireless ones and match its ssid to currently connected one.
		ScanResult currentResult = null;
		for(ScanResult temp : results){
			if(temp.BSSID.equals(wifiInfo.getBSSID())){
				currentResult = temp;
				break;
			}
		}
		//This part below sets the Security field in the app.
		TextView text3 = (TextView) findViewById(R.id.textView11);
		if(currentResult != null){
			text3.setText(currentResult.capabilities);
		}else{text3.setText("Error: Not Found");}
		//This sets the link speed field.
		TextView text4 = (TextView) findViewById(R.id.textView12);
		text4.setText(wifiInfo.getLinkSpeed() + "Mbps");
		
		//Below is the code for showing the data transferred and code to update it.
		zeroUp = TrafficStats.getTotalTxBytes();
		zeroDown = TrafficStats.getTotalRxBytes();
		up = TrafficStats.getTotalTxBytes() - zeroUp;
		down = TrafficStats.getTotalRxBytes() - zeroDown;
		text5 = (TextView) findViewById(R.id.textView13);
		text5.setText(down + " bytes.");
		text6 = (TextView) findViewById(R.id.textView14);
		text6.setText(up +" bytes.");
		aHandler = new Handler();
		aHandler.post(update);
	}
	private Runnable update = new Runnable() {
    	public void run() {
    		up = TrafficStats.getTotalTxBytes() - zeroUp;
    		down = TrafficStats.getTotalRxBytes() - zeroDown;
    		text5.setText(down + " bytes.");
    		text6.setText(up +" bytes.");
    		aHandler.postDelayed(this, 1000);

    	}
    };
}
